<template>
  <div class="homework-container">
    <el-card class="homework-list" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>作业列表</span>
          <el-button type="primary" @click="showCreateDialog">发布作业</el-button>
        </div>
      </template>
      
      <el-table :data="homeworkList" style="width: 100%">
        <el-table-column prop="title" label="作业标题" />
        <el-table-column prop="description" label="作业描述" show-overflow-tooltip />
        <el-table-column prop="studentName" label="学生" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="viewHomework(scope.row)">
              查看
            </el-button>
            <el-button type="success" link @click="gradeHomework(scope.row)" 
                       v-if="scope.row.status === 1">
              批改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建作业对话框 -->
    <el-dialog v-model="createDialogVisible" title="发布作业" width="60%" v-loading="loading">
      <el-form :model="homeworkForm" label-width="100px">
        <el-form-item label="选择学生" required>
          <el-select v-model="homeworkForm.tutoringBookingId" placeholder="请选择学生">
            <el-option
              v-for="booking in bookings"
              :key="booking.id"
              :label="booking.studentName + ' - ' + booking.subject"
              :value="booking.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="作业标题" required>
          <el-input v-model="homeworkForm.title" />
        </el-form-item>
        <el-form-item label="作业描述">
          <el-input v-model="homeworkForm.description" type="textarea" />
        </el-form-item>
        
        <!-- 添加课程分类和知识点选择 -->
        <el-form-item label="课程分类" required>
          <el-select 
            v-model="selectedCategory" 
            placeholder="请选择课程分类"
            @change="handleCategoryChange"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 题目列表 -->
        <el-divider>题目列表</el-divider>
        <div class="ai-actions">
          <el-button type="primary" @click="showAIGenerateDialog">
            使用AI生成题目
          </el-button>
        </div>
        <div v-for="(question, index) in questions" :key="index" class="question-item">
          <el-form-item :label="'题目 ' + (index + 1)" required>
            <div class="question-header">
              <el-select v-model="question.questionType" class="question-type-select">
                <el-option label="选择题" :value="1" />
                <el-option label="填空题" :value="2" />
                <el-option label="简答题" :value="3" />
                <el-option label="综合题" :value="4" />
              </el-select>
              <el-button type="danger" @click="removeQuestion(index)">删除题目</el-button>
            </div>
            <el-input v-model="question.questionContent" type="textarea" />
          </el-form-item>
          
          <!-- 选择题选项 -->
          <template v-if="question.questionType === 1">
            <el-form-item label="选项">
              <div v-for="(option, optIndex) in (question.options || [])" :key="optIndex">
                <el-input v-model="option.content" class="option-input">
                  <template #prepend>{{ String.fromCharCode(65 + optIndex) }}</template>
                  <template #append>
                    <el-button @click="removeOption(question, optIndex)" v-if="(question.options || []).length > 2">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </div>
              <el-button type="primary" link @click="addOption(question)" :disabled="(question.options || []).length >= 6">
                添加选项
              </el-button>
            </el-form-item>
          </template>
          
          <!-- 添加知识点选择 -->
          <el-form-item label="知识点" required>
            <el-select 
              v-model="question.knowledgePointId"
              placeholder="请选择知识点"
              :disabled="!selectedCategory"
              style="width: 100%"
            >
              <el-option
                v-for="point in knowledgePoints"
                :key="point.id"
                :label="point.name"
                :value="point.id"
              >
                <span>{{ point.name }}</span>
                <small style="color: #8492a6; margin-left: 8px">{{ point.description }}</small>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="标准答案" required>
            <template v-if="question.questionType === 1">
              <el-select v-model="question.standardAnswer">
                <el-option 
                  v-for="(_, index) in question.options" 
                  :key="index"
                  :label="String.fromCharCode(65 + index)"
                  :value="String.fromCharCode(65 + index)"
                />
              </el-select>
            </template>
            <template v-else>
              <el-input 
                v-model="question.standardAnswer"
                :type="question.questionType === 4 ? 'textarea' : 'text'"
                :rows="question.questionType === 4 ? 4 : 1"
              />
            </template>
          </el-form-item>
          
          <el-form-item label="分值">
            <el-input-number v-model="question.score" :min="0" />
          </el-form-item>
        </div>
        
        <el-button type="primary" @click="addQuestion">添加题目</el-button>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHomework">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批改作业对话框 -->
    <el-dialog v-model="gradeDialogVisible" title="批改作业" width="60%">
      <template v-if="currentHomework">
        <h3>{{ currentHomework.title }}</h3>
        <p>{{ currentHomework.description }}</p>
        
        <div class="grade-actions">
          <el-button type="primary" @click="handleAutoGradeAll">
            自动批改全部
          </el-button>
        </div>
        
        <el-form>
          <div v-for="(question, index) in currentHomework.questions" :key="index" 
               class="question-grade">
            <h4>题目 {{ index + 1 }}</h4>
            <p class="question-content">{{ question.questionContent }}</p>
            
            <!-- 显示选择题选项 -->
            <template v-if="question.questionType === 1 && question.questionOptions">
              <div class="options-list">
                <p v-for="(option, optIndex) in JSON.parse(question.questionOptions)" 
                   :key="optIndex" class="option-item">
                  {{ String.fromCharCode(65 + optIndex) }}. {{ option.content }}
                </p>
              </div>
            </template>

            <div class="answer-section">
              <div class="student-answer">
                <h5>学生答案：</h5>
                <p v-if="question.studentAnswer?.answerContent" class="answer-content">
                  {{ question.questionType === 1 ? 
                      question.studentAnswer.answerContent : 
                      question.studentAnswer.answerContent }}
                </p>
                <p v-else class="no-answer">未作答</p>
              </div>

              <div class="standard-answer">
                <h5>标准答案：</h5>
                <p>{{ question.standardAnswer }}</p>
              </div>
            </div>
            
            <template v-if="question.studentAnswer?.answerContent">
              <div class="grade-actions">
                <el-button type="primary" size="small" 
                          @click="handleAutoGrade(question.studentAnswer.id)">
                  自动批改此题
                </el-button>
              </div>
              
              <el-form-item label="评语">
                <el-input v-model="question.studentAnswer.teacherComment" 
                          type="textarea" 
                          :rows="3"
                          placeholder="请输入评语" />
              </el-form-item>
              
              <el-form-item label="得分">
                <el-input-number v-model="question.studentAnswer.score" 
                               :min="0" 
                               :max="question.score"
                               :step="1" />
                <span class="total-score">满分：{{ question.score }}分</span>
              </el-form-item>
            </template>
            <template v-else>
              <p class="no-answer">学生尚未提交答案，无法批改</p>
            </template>
          </div>
        </el-form>
        
        <div class="dialog-footer">
          <el-button @click="gradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrade">提交批改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- AI生成题目对话框 -->
    <el-dialog v-model="aiGenerateDialogVisible" title="AI生成题目" width="40%">
      <el-form :model="aiGenerateForm" label-width="100px">
        <el-form-item label="知识点" required>
          <el-select 
            v-model="aiGenerateForm.knowledgePointId"
            placeholder="请选择知识点"
            style="width: 100%"
          >
            <el-option
              v-for="point in knowledgePoints"
              :key="point.id"
              :label="point.name"
              :value="point.id"
            >
              <span>{{ point.name }}</span>
              <small style="color: #8492a6; margin-left: 8px">{{ point.description }}</small>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="主题内容" required>
          <el-input 
            v-model="aiGenerateForm.topic"
            type="textarea"
            :rows="3"
            placeholder="请输入要生成题目的主题内容"
          />
        </el-form-item>
        
        <el-form-item label="题目类型" required>
          <el-select v-model="aiGenerateForm.questionType">
            <el-option label="选择题" :value="1" />
            <el-option label="填空题" :value="2" />
            <el-option label="简答题" :value="3" />
            <el-option label="综合题" :value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目数量" required>
          <el-input-number v-model="aiGenerateForm.questionCount" :min="1" :max="10" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="aiGenerateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAIGenerate" :loading="loading">
            生成题目
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import useUserInfoStore from '@/stores/userInfo'
import { 
  getTeacherHomeworks,
  createHomework,
  getHomework,
  gradeAnswer,
  autoGradeAnswer,
  autoGradeHomework,
  updateHomeworkStatus,
  getStudentAnswers,
  createMistakeRecord,
  setHomeworkKnowledgePoints,
  generateQuestionsByAI
} from '@/api/homework'
import { getTeacherBookings, tutoringService } from '@/api/tutoring'
import { lessonCategoryListService } from '@/api/lesson'
import { getKnowledgePointsByCategory } from '@/api/knowledgePoint'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const userStore = useUserInfoStore()
const route = useRoute()
const router = useRouter()
const homeworkList = ref([])
const createDialogVisible = ref(false)
const gradeDialogVisible = ref(false)
const currentHomework = ref(null)
const bookings = ref([])
const loading = ref(false)
const knowledgePointsLoading = ref(false)
const categories = ref([])
const knowledgePoints = ref([])
const selectedCategory = ref(null)
const aiGenerateDialogVisible = ref(false)
const aiGenerateForm = ref({
  questionType: 1,
  questionCount: 1,
  knowledgePointId: null,
  topic: ''
})

// 计算属性：检查用户是否已登录且是教师
const isTeacherLoggedIn = computed(() => {
  const userInfo = userStore.info
  return userInfo && userInfo.id && userInfo.role === 1
})

const homeworkForm = ref({
  title: '',
  description: '',
  tutoringBookingId: null,
  homeworkType: 1,  // 添加默认作业类型
  categoryId: null  // 添加分类ID
})

const questions = ref([])

// 检查用户权限
const checkTeacherAuth = async () => {
  try {
    if (!userStore.info) {
      await userStore.getUserInfo()
    }

    if (!isTeacherLoggedIn.value) {
      ElMessage.error('只有教师才能访问此页面')
      router.push('/home')
      return false
    }

    return true
  } catch (error) {
    ElMessage.error('获取用户信息失败，请重新登录')
    router.push('/login')
    return false
  }
}

// 获取教师的家教预约列表
const fetchBookings = async () => {
  if (!await checkTeacherAuth()) return

  try {
    loading.value = true
    const res = await tutoringService.getTeacherBookings()
    console.log('获取到的预约列表:', res.data)
    // 确保每个预约对象都有必要的字段
    bookings.value = res.data.map(booking => ({
      ...booking,
      studentName: booking.studentName || '未知学生',
      subject: booking.subject || booking.tutoringTitle || '未知科目'
    }))
  } catch (error) {
    console.error('获取家教预约失败:', error)
    ElMessage.error('获取家教预约失败')
  } finally {
    loading.value = false
  }
}

// 获取作业列表
const fetchHomeworkList = async () => {
  if (!await checkTeacherAuth()) return

  try {
    loading.value = true
    const res = await getTeacherHomeworks(userStore.info.id)
    homeworkList.value = res.data
  } catch (error) {
    ElMessage.error('获取作业列表失败')
  } finally {
    loading.value = false
  }
}

// 获取课程分类列表
const fetchCategories = async () => {
  try {
    const res = await lessonCategoryListService()
    if (res.code === 0) {
      categories.value = res.data
      console.log('获取到的课程分类列表:', categories.value)
      
      // 如果有从路由传来的分类ID，自动选择对应的分类
      if (route.query.categoryId || route.params.categoryId) {
        const categoryId = route.query.categoryId || route.params.categoryId
        selectedCategory.value = Number(categoryId)
        handleCategoryChange(Number(categoryId))
      }
    }
  } catch (error) {
    console.error('获取课程分类失败:', error)
    ElMessage.error('获取课程分类失败')
  }
}

// 处理分类变化
const handleCategoryChange = async (categoryId) => {
  console.log('分类变化，categoryId:', categoryId)
  knowledgePoints.value = []
  homeworkForm.value.categoryId = null
  
  // 清空所有题目的知识点
  questions.value.forEach(q => {
    q.knowledgePointId = null
  })
  
  if (!categoryId) {
    return
  }
  
  try {
    knowledgePointsLoading.value = true
    homeworkForm.value.categoryId = Number(categoryId)
    console.log('正在获取分类知识点，分类ID:', categoryId, typeof categoryId)
    const res = await getKnowledgePointsByCategory(Number(categoryId))
    console.log('API响应:', res)
    if (res.code === 0) {
      knowledgePoints.value = res.data || []
      console.log('设置知识点列表:', knowledgePoints.value)
    } else {
      console.error('获取知识点列表返回错误:', res)
      ElMessage.warning(res.msg || '获取知识点列表失败')
      knowledgePoints.value = []
    }
  } catch (error) {
    console.error('获取知识点列表失败:', error)
    ElMessage.error('获取知识点列表失败：' + (error.response?.data?.message || error.message))
    knowledgePoints.value = []
  } finally {
    knowledgePointsLoading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = async () => {
  if (!await checkTeacherAuth()) return

  try {
    loading.value = true
    // 重置表单数据
    homeworkForm.value = {
      title: '',
      description: '',
      tutoringBookingId: route.query.bookingId || route.params.bookingId || null,
      homeworkType: 1,
      categoryId: null
    }
    selectedCategory.value = null
    knowledgePoints.value = []
    questions.value = []
    
    // 获取必要数据
    await Promise.all([
      fetchBookings(),
      fetchCategories()
    ])
    
    if (bookings.value.length === 0) {
      ElMessage.warning('暂无可用的家教预约，请先创建家教预约')
      return
    }

    createDialogVisible.value = true
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 添加题目
const addQuestion = () => {
  const newQuestion = {
    questionType: 1, // 默认选择题
    questionContent: '',
    standardAnswer: '',
    score: 10,
    knowledgePointId: null, // 添加知识点ID字段
    options: [
      { content: '' },
      { content: '' }
    ]
  }
  
  // 确保选择题有初始选项
  if (newQuestion.questionType === 1 && (!newQuestion.options || !newQuestion.options.length)) {
    newQuestion.options = [
      { content: '' },
      { content: '' }
    ]
  }
  
  questions.value.push(newQuestion)
}

// 删除题目
const removeQuestion = (index) => {
  questions.value.splice(index, 1)
}

// 添加选项（仅选择题）
const addOption = (question) => {
  if (!question.options) {
    question.options = []
  }
  if (question.options.length < 6) { // 最多6个选项
    question.options.push({ content: '' })
  }
}

// 删除选项
const removeOption = (question, optIndex) => {
  if (!question.options) {
    question.options = []
    return
  }
  if (question.options.length > 2) { // 至少保留2个选项
    question.options.splice(optIndex, 1)
    // 如果删除的是当前选中的答案，清空答案
    if (question.standardAnswer === String.fromCharCode(65 + optIndex)) {
      question.standardAnswer = ''
    }
  }
}

// 提交作业
const submitHomework = async () => {
  if (!homeworkForm.value.title || !homeworkForm.value.tutoringBookingId || questions.value.length === 0) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (!homeworkForm.value.categoryId) {
    ElMessage.warning('请选择课程分类')
    return
  }

  // 验证每个题目
  for (const question of questions.value) {
    if (!question.questionContent || !question.standardAnswer || !question.score || !question.knowledgePointId) {
      ElMessage.warning('请完整填写每道题目的内容、答案、分值和知识点')
      return
    }
    
    // 验证选择题选项
    if (question.questionType === 1) {
      if (!question.options || question.options.length < 2) {
        ElMessage.warning('选择题至少需要2个选项')
        return
      }
      if (question.options.some(opt => !opt.content)) {
        ElMessage.warning('请填写所有选项内容')
        return
      }
    }
  }

  try {
    loading.value = true
    // 处理题目数据
    const processedQuestions = questions.value.map(q => {
      const questionData = {
        questionType: q.questionType,
        questionContent: q.questionContent,
        standardAnswer: q.standardAnswer,
        score: q.score,
        knowledgePointId: q.knowledgePointId
      }
      
      // 如果是选择题，将选项转换为字符串
      if (q.questionType === 1 && q.options) {
        questionData.questionOptions = JSON.stringify(q.options)
      }
      
      return questionData
    })

    // 计算作业类型：如果所有题目类型相同，则使用该类型；否则使用混合类型（5）
    const types = new Set(questions.value.map(q => q.questionType))
    homeworkForm.value.homeworkType = types.size === 1 ? questions.value[0].questionType : 5

    const requestData = {
      homework: {
        title: homeworkForm.value.title,
        description: homeworkForm.value.description,
        tutoringBookingId: homeworkForm.value.tutoringBookingId,
        homeworkType: homeworkForm.value.homeworkType,
        categoryId: homeworkForm.value.categoryId
      },
      questions: processedQuestions
    }

    console.log('提交作业数据:', requestData)
    // 创建作业
    const res = await createHomework(requestData)
    console.log('创建作业响应:', res)

    ElMessage.success('作业发布成功')
    createDialogVisible.value = false
    fetchHomeworkList()
  } catch (error) {
    console.error('作业发布失败:', error)
    ElMessage.error('作业发布失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查看作业
const viewHomework = async (homework) => {
  try {
    const res = await getHomework(homework.id)
    console.log('获取到的作业详情:', JSON.stringify(res.data, null, 2))
    
    // 获取学生答案
    try {
      // 从预约信息中获取学生ID
      const tutoringBookingId = res.data.tutoringBookingId
      if (!tutoringBookingId) {
        console.error('未找到家教预约ID')
        throw new Error('未找到家教预约ID')
      }
      
      // 获取预约信息
      console.log('正在获取预约信息，预约ID:', tutoringBookingId)
      console.log('请求URL:', `/api/tutoring/booking/${tutoringBookingId}`)
      const bookingRes = await tutoringService.getTutoringBooking(tutoringBookingId)
      console.log('获取到的预约信息:', JSON.stringify(bookingRes.data, null, 2))
      
      const studentId = bookingRes.data?.studentId
      if (!studentId) {
        console.error('未找到学生ID，完整的预约数据:', bookingRes)
        throw new Error('未找到学生ID')
      }
      
      console.log('正在获取学生答案，作业ID:', homework.id, '学生ID:', studentId)
      const answersRes = await getStudentAnswers(homework.id, studentId)
      console.log('获取到的学生答案:', JSON.stringify(answersRes.data, null, 2))
      
      // 将答案关联到对应的问题
      if (answersRes.data && Array.isArray(answersRes.data)) {
        res.data.questions.forEach(question => {
          const answer = answersRes.data.find(a => a.questionId === question.id)
          if (answer) {
            question.studentAnswer = answer
            console.log(`问题 ${question.id} 设置答案:`, answer)
          } else {
            console.log(`问题 ${question.id} 未找到对应的答案`)
          }
        })
      } else {
        console.error('获取到的答案数据格式不正确:', answersRes.data)
      }
    } catch (error) {
      console.error('获取学生答案失败:', error)
      console.error('错误详情:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        config: error.config
      })
      ElMessage.error('获取学生答案失败：' + (error.response?.data?.message || error.message))
      return
    }
    
    currentHomework.value = res.data
    gradeDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败：' + (error.response?.data?.message || error.message))
  }
}

// 批改作业
const gradeHomework = async (homework) => {
  try {
    const res = await getHomework(homework.id)
    console.log('获取到的作业详情:', JSON.stringify(res.data, null, 2))
    
    // 获取学生答案
    try {
      // 从预约信息中获取学生ID
      const tutoringBookingId = res.data.tutoringBookingId
      if (!tutoringBookingId) {
        console.error('未找到家教预约ID')
        throw new Error('未找到家教预约ID')
      }
      
      // 获取预约信息
      console.log('正在获取预约信息，预约ID:', tutoringBookingId)
      const bookingRes = await tutoringService.getTutoringBooking(tutoringBookingId)
      console.log('获取到的预约信息:', JSON.stringify(bookingRes.data, null, 2))
      
      const studentId = bookingRes.data.studentId
      if (!studentId) {
        console.error('未找到学生ID')
        throw new Error('未找到学生ID')
      }
      
      console.log('正在获取学生答案，作业ID:', homework.id, '学生ID:', studentId)
      const answersRes = await getStudentAnswers(homework.id, studentId)
      console.log('获取到的学生答案:', JSON.stringify(answersRes.data, null, 2))
      
      // 将答案关联到对应的问题
      if (answersRes.data && Array.isArray(answersRes.data)) {
        res.data.questions.forEach(question => {
          const answer = answersRes.data.find(a => a.questionId === question.id)
          if (answer) {
            question.studentAnswer = answer
            console.log(`问题 ${question.id} 设置答案:`, answer)
          } else {
            console.log(`问题 ${question.id} 未找到对应的答案`)
          }
        })
      } else {
        console.error('获取到的答案数据格式不正确:', answersRes.data)
      }
    } catch (error) {
      console.error('获取学生答案失败:', error)
      ElMessage.error('获取学生答案失败：' + (error.response?.data?.message || error.message))
      return
    }
    
    currentHomework.value = res.data
    gradeDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败：' + (error.response?.data?.message || error.message))
  }
}

// 提交批改
const submitGrade = async () => {
  try {
    console.log('准备提交批改，当前作业数据:', JSON.stringify(currentHomework.value, null, 2))
    
    // 检查是否所有已提交答案的题目都已批改
    const ungraded = currentHomework.value.questions.some(q => {
      const hasAnswer = q.studentAnswer && (q.studentAnswer.id || q.studentAnswer.answerId)
      const needsGrading = !q.studentAnswer.score || !q.studentAnswer.teacherComment
      console.log(`问题检查 - 有答案: ${hasAnswer}, 需要批改: ${needsGrading}`)
      return hasAnswer && needsGrading
    })
    
    if (ungraded) {
      ElMessage.warning('请完成所有已提交答案的题目批改')
      return
    }

    // 只提交已有答案的题目的批改
    for (const question of currentHomework.value.questions) {
      const answerId = question.studentAnswer?.id || question.studentAnswer?.answerId
      if (answerId) {
        console.log('提交批改答案:', {
          answerId,
          comment: question.studentAnswer.teacherComment,
          score: question.studentAnswer.score
        })
        
        await gradeAnswer(
          answerId,
          question.studentAnswer.teacherComment || '',
          question.studentAnswer.score || 0
        )
      }
    }

    // 更新作业状态为已批改（状态码2）
    await updateHomeworkStatus(currentHomework.value.id, 2)

    ElMessage.success('批改完成')
    gradeDialogVisible.value = false
    fetchHomeworkList()
  } catch (error) {
    console.error('批改失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(error.response.data?.message || '批改失败')
    } else {
      console.error('网络错误:', error.message)
      ElMessage.error('网络错误，请检查网络连接')
    }
  }
}

// 获取作业详情
const getHomeworkDetail = async (homeworkId) => {
  try {
    const res = await getHomework(homeworkId)
    console.log('获取到的作业详情:', JSON.stringify(res.data, null, 2))
    
    // 获取学生答案
    try {
      // 从预约信息中获取学生ID
      const tutoringBookingId = res.data.tutoringBookingId
      if (!tutoringBookingId) {
        console.error('未找到家教预约ID')
        throw new Error('未找到家教预约ID')
      }
      
      // 获取预约信息
      console.log('正在获取预约信息，预约ID:', tutoringBookingId)
      const bookingRes = await tutoringService.getTutoringBooking(tutoringBookingId)
      console.log('获取到的预约信息:', JSON.stringify(bookingRes.data, null, 2))
      
      const studentId = bookingRes.data.studentId
      if (!studentId) {
        console.error('未找到学生ID')
        throw new Error('未找到学生ID')
      }
      
      console.log('正在获取学生答案，作业ID:', homeworkId, '学生ID:', studentId)
      const answersRes = await getStudentAnswers(homeworkId, studentId)
      console.log('获取到的学生答案:', JSON.stringify(answersRes.data, null, 2))
      
      // 将答案关联到对应的问题
      if (answersRes.data && Array.isArray(answersRes.data)) {
        res.data.questions.forEach(question => {
          const answer = answersRes.data.find(a => a.questionId === question.id)
          if (answer) {
            question.studentAnswer = answer
            console.log(`问题 ${question.id} 设置答案:`, answer)
          } else {
            console.log(`问题 ${question.id} 未找到对应的答案`)
          }
        })
      } else {
        console.error('获取到的答案数据格式不正确:', answersRes.data)
      }
    } catch (error) {
      console.error('获取学生答案失败:', error)
      ElMessage.error('获取学生答案失败：' + (error.response?.data?.message || error.message))
      return
    }
    
    currentHomework.value = res.data
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败：' + (error.response?.data?.message || error.message))
    throw error
  }
}

// 自动批改单个答案
const handleAutoGrade = async (answerId) => {
  try {
    await autoGradeAnswer(answerId)
    // 重新获取作业详情以更新显示
    if (currentHomework.value?.id) {
      await getHomeworkDetail(currentHomework.value.id)
      ElMessage.success('自动批改完成')
    }
  } catch (error) {
    console.error('自动批改失败:', error)
    ElMessage.error('自动批改失败：' + (error.response?.data?.message || error.message))
  }
}

// 自动批改全部答案
const handleAutoGradeAll = async () => {
  try {
    if (!currentHomework.value || !currentHomework.value.id) {
      throw new Error('作业信息不完整')
    }
    
    // 从预约信息中获取学生ID
    const tutoringBookingId = currentHomework.value.tutoringBookingId
    if (!tutoringBookingId) {
      throw new Error('未找到家教预约ID')
    }
    
    const bookingRes = await tutoringService.getTutoringBooking(tutoringBookingId)
    const studentId = bookingRes.data.studentId
    if (!studentId) {
      throw new Error('未找到学生ID')
    }
    
    await autoGradeHomework(currentHomework.value.id, studentId)
    // 重新获取作业详情以更新显示
    await getHomeworkDetail(currentHomework.value.id)
    ElMessage.success('全部题目自动批改完成')
  } catch (error) {
    console.error('自动批改失败:', error)
    ElMessage.error('自动批改失败：' + (error.response?.data?.message || error.message))
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 未完成
    1: 'warning', // 已提交
    2: 'success'  // 已批改
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '未完成',
    1: '已提交',
    2: '已批改'
  }
  return texts[status] || '未知'
}

// 显示AI生成对话框
const showAIGenerateDialog = () => {
  if (!selectedCategory.value) {
    ElMessage.warning('请先选择课程分类')
    return
  }
  
  // 重置表单
  aiGenerateForm.value = {
    questionType: 1,
    questionCount: 1,
    knowledgePointId: null,
    topic: ''
  }
  
  aiGenerateDialogVisible.value = true
}

// 使用AI生成题目
const handleAIGenerate = async () => {
  try {
    if (!selectedCategory.value || !aiGenerateForm.value.questionType) {
      ElMessage.warning('请选择课程分类和题目类型')
      return
    }

    // 验证是否有可用的知识点
    if (!knowledgePoints.value || knowledgePoints.value.length === 0) {
      ElMessage.warning('当前课程分类下没有可用的知识点，请先添加知识点')
      return
    }

    // 添加知识点选择的验证
    if (!aiGenerateForm.value.knowledgePointId) {
      ElMessage.warning('请选择知识点')
      return
    }

    // 验证主题内容
    if (!aiGenerateForm.value.topic.trim()) {
      ElMessage.warning('请输入主题内容')
      return
    }

    loading.value = true
    const res = await generateQuestionsByAI(
      selectedCategory.value,
      aiGenerateForm.value.knowledgePointId,
      aiGenerateForm.value.questionType,
      aiGenerateForm.value.questionCount,
      aiGenerateForm.value.topic
    )

    if (res.code === 0 && res.data) {
      // 将生成的题目添加到题目列表
      questions.value.push(...res.data)
      aiGenerateDialogVisible.value = false
      ElMessage.success('AI生成题目成功')
    } else {
      ElMessage.error(res.msg || 'AI生成题目失败')
    }
  } catch (error) {
    console.error('AI生成题目失败:', error)
    ElMessage.error('AI生成题目失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    loading.value = true
    if (await checkTeacherAuth()) {
      await fetchHomeworkList()
    }
  } catch (error) {
    ElMessage.error('初始化失败：' + error.message)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.homework-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-item {
  border: 1px solid #eee;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.question-type-select {
  width: 150px;
}

.option-input {
  margin-bottom: 10px;
  width: 100%;
}

.option-input :deep(.el-input-group__append) {
  padding: 0;
}

.question-grade {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.question-content {
  font-size: 16px;
  margin: 10px 0;
  white-space: pre-wrap;
}

.options-list {
  margin: 10px 0;
  padding-left: 20px;
}

.option-item {
  margin: 5px 0;
}

.answer-section {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.student-answer, .standard-answer {
  margin: 10px 0;
}

.student-answer h5, .standard-answer h5 {
  color: #606266;
  margin-bottom: 5px;
}

.answer-content {
  white-space: pre-wrap;
  color: #303133;
}

.no-answer {
  color: #909399;
  font-style: italic;
}

.total-score {
  margin-left: 10px;
  color: #606266;
}

.grade-actions {
  margin-bottom: 20px;
  text-align: right;
}

.ai-actions {
  margin-bottom: 20px;
  text-align: right;
}
</style> 